<template>
  <a-modal
    title="权限操作"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    okText="分配权限"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-tree
        :checkable="true"
        :autoExpandParent="autoExpandParent"
        :defaultExpandAll="defaultExpandAll"
        v-model="checkedKeys"
        @check="updatePermission"
        :treeData="treeData"/>
    </a-spin>
  </a-modal>
</template>
<script>
  import ATree from 'ant-design-vue/es/tree';
  import { getPermissions, getRoleMenuByRoleId } from '@/api/manage';
  import { customRolePermission } from '@/api/menu'

    export default {
      name: 'RoleAssignPermissionModel',
      components: {
        ATree
      },
      data() {
          return {
            visible: false,
            confirmLoading: false,
            autoExpandParent: true,
            defaultExpandAll: true,
            checkedKeys: [],
            treeData: [],
            roleId: ''
          }
      },
      methods: {
        show (roleId) {
          const _this = this;
          _this.roleId = roleId;
          _this.confirmLoading = true;
          getPermissions().then(res => {
            this.treeData = res.data;
            return true
          }).then(() => {
            getRoleMenuByRoleId(roleId).then(res => {
              this.checkedKeys = res.data;
            })
            _this.confirmLoading = false
          }).catch(() => {
            _this.confirmLoading = true
          });
          this.visible = true
        },
        close () {
          this.visible = false
          this.$emit('close');
        },
        handleOk () {
          const _this = this;
          _this.confirmLoading = true;
          console.log(_this.checkedKeys);
          customRolePermission(_this.roleId, _this.checkedKeys)
            .then(res => {
              if (res) {
                _this.$message.success('保存成功');
                _this.$emit('ok');
              } else {
                _this.$message.warning('保存失败');
              }
            }).finally(() => {
              _this.confirmLoading = false
              _this.close()
          });
        },
        handleCancel () {
          this.close()
        },
        updatePermission: function(checkedKeys, e) {
          console.log('updatePermission:', checkedKeys, e);
          this.checkedKeys = checkedKeys;
        }
      }
    }
</script>

<style scoped>

</style>
